package com.sensetime.audiodeocde;

import android.content.Context;
import android.os.Environment;
import android.util.Log;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;

public class FileUtils {
    private static final String TAG =  FileUtils.class.getSimpleName();
    public static String AUDIO_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "audio";

    public static void makeAudioDir() {
        final File file = new File(AUDIO_DIR);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public static void copyAssertDir(Context context, String fileName) {
        String[] files = null;

        try {
            files = context.getAssets().list(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String folderPath = null;
        File dataDir = context.getExternalFilesDir(null);
        if (dataDir != null) {
            folderPath = dataDir.getAbsolutePath() + File.separator + fileName;

            File folder = new File(folderPath);

            if (!folder.exists()) {
                folder.mkdir();
            }
        }
        for (int i = 0; i < files.length; i++) {
            String str = files[i];
            String childFile = folderPath + File.separator + str;
            try {
                String[] childFiles = context.getAssets().list(childFile);
                if (childFiles != null && childFiles.length > 0) { //这是一个目录，需要对目录下的文件进行拷贝
                    for (int k = 0; k < childFiles.length; k++) {
                        String strChild = files[k];
                        String cFile = childFile + File.separator + strChild;
                        copyFileToExternal(context, cFile);
                    }
                } else {
                    copyAssertDir(context, childFile);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public static boolean copyFileToExternal(Context context, String fileName) {
        String path = getExternalFilePath(context, fileName);
        Log.e(TAG, "external file path: " + path);
        if (path != null) {
            File file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
//            if (className.contains("oms")&& fileName.contains("meta")){
//                if (file.exists()){
//                    try {
//                        file.delete();
//                    }catch (Exception e){
//                        e.printStackTrace();
//                    }
//                }
//            }
            if (!file.exists()) {
                try {
                    if (file.exists()) {
                        file.delete();
                    }
                    file.createNewFile();
                    String pathName = fileName;
                    InputStream in = context.getAssets().open(pathName);
                    if (in == null) {
                        Log.e("copyMode", "the src is not existed:assets fileNotFound--->"+pathName);
                        return false;
                    }
                    OutputStream out = new FileOutputStream(file);
                    byte[] buffer = new byte[4096];
                    int n;
                    while ((n = in.read(buffer)) > 0) {
                        out.write(buffer, 0, n);
                    }
                    in.close();
                    out.close();
                } catch (IOException e) {
                    Log.e("init", "copyFileToExternal: " +  fileName, e);
                    file.delete();
                    return false;
                }
            }
        }
        return true;
    }

    public static boolean copyFileToExternal(Context context, String inFileName, String outFileName, String className) {
        String path = getExternalFilePath(context, className + File.separator + outFileName);
        Log.e(TAG, "copyFileToExternal external file path: " + path);
        if (path != null) {
            File file = new File(path);
            if (!file.exists()) {
                try {
                    if (!Objects.requireNonNull(file.getParentFile().getParentFile()).exists()) {
                        file.getParentFile().getParentFile().mkdirs();
                    }
                    if (!Objects.requireNonNull(file.getParentFile()).exists()) {
                        file.getParentFile().mkdirs();
                    }
                    file.createNewFile();

                    InputStream in = context.getAssets().open(className + File.separator + inFileName);
                    if (in == null) {
                        Log.e("copyMode", "copyFileToExternal the src is not existed");
                        return false;
                    }
                    OutputStream out = new FileOutputStream(file);
                    byte[] buffer = new byte[4096];
                    int n;
                    while ((n = in.read(buffer)) > 0) {
                        out.write(buffer, 0, n);
                    }
                    in.close();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    file.delete();
                    return false;
                }
            }
        }
        return true;
    }

    public static boolean copyFileToInternal(Context context, String fileName, String className) {
        String path = new File(context.getFilesDir().getAbsolutePath()).getParent() + File.separator + fileName;
        Log.e(TAG, "copyFileToInternal internal file path: " + path);
        if (path != null) {
            File file = new File(path);
//            if (className.contains("oms")&& fileName.contains("meta")){
//                if (file.exists()){
//                    try {
//                        file.delete();
//                    }catch (Exception e){
//                        e.printStackTrace();
//                    }
//                }
//            }
            if (!file.exists()) {
                try {
                    if (file.exists()) {
                        file.delete();
                    }
                    file.createNewFile();

                    InputStream in = context.getAssets().open(className + File.separator + fileName);
                    if (in == null) {
                        Log.e("copyMode", "the src is not existed");
                        return false;
                    }
                    OutputStream out = new FileOutputStream(file);
                    byte[] buffer = new byte[4096];
                    int n;
                    while ((n = in.read(buffer)) > 0) {
                        out.write(buffer, 0, n);
                    }
                    in.close();
                    out.close();
                } catch (IOException e) {
                    Log.e("init", "copyFileToExternal: " + className + File.separator + fileName, e);
                    file.delete();
                    return false;
                }
            }
        }
        return true;
    }

    public static String getExternalFilePath(Context context, String fileName) {
        String path = null;
        File dataDir = context.getExternalFilesDir(null);
        if (dataDir != null) {
            path = dataDir.getAbsolutePath() + File.separator + fileName;
        }
        return path;
    }

    public static void savePcm(byte[] dataByteBuffer, String fileName) {
        if (dataByteBuffer != null && dataByteBuffer.length > 0) {
            Log.d(TAG, "dataByteBuffer length: " + dataByteBuffer.length);
            File fileaudio = new File(AUDIO_DIR + fileName);
            if (fileaudio.exists()) {
                fileaudio.delete();
            }
            try (FileOutputStream fos = new FileOutputStream(fileaudio)) {
                if (null != fos) {
                    fos.write(dataByteBuffer);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void copyAssetsDir2Phone(Context activity, String filePath) {
        try {
            String[] fileList = activity.getAssets().list(filePath);
            if (fileList.length > 0) {//如果是目录
                File file = new File(activity.getExternalFilesDir(null), filePath);
                file.mkdirs();//如果文件夹不存在，则递归
                for (String fileName : fileList) {
                    filePath = filePath + File.separator + fileName;

                    copyAssetsDir2Phone(activity, filePath);

                    filePath = filePath.substring(0, filePath.lastIndexOf(File.separator));
                    Log.e("oldPath", filePath);
                }
            } else {//如果是文件
                InputStream inputStream = activity.getAssets().open(filePath);
                File file = new File(activity.getExternalFilesDir(null), filePath);
                Log.i("copyAssets2Phone", "file:" + file);
                if (!file.exists() || file.length() == 0) {
                    FileOutputStream fos = new FileOutputStream(file);
                    int len = -1;
                    byte[] buffer = new byte[1024];
                    while ((len = inputStream.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                    }
                    fos.flush();
                    inputStream.close();
                    fos.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将文件从assets目录，考贝到 /data/data/包名/files/ 目录中。assets 目录中的文件，会不经压缩打包至APK包中，使用时还应从apk包中导出来
     *
     * @param fileName 文件名,如aaa.txt
     */
    public static void copyAssetsFile2Phone(Context activity, String fileName) {
        try {
            InputStream inputStream = activity.getAssets().open(fileName);
            //getFilesDir() 获得当前APP的安装路径 /data/data/包名/files 目录
            File file = new File(activity.getExternalFilesDir(null), fileName);
            if (!file.exists() || file.length() == 0) {
                FileOutputStream fos = new FileOutputStream(file);//如果文件不存在，FileOutputStream会自动创建文件
                int len = -1;
                byte[] buffer = new byte[1024];
                while ((len = inputStream.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                fos.flush();//刷新缓存区
                inputStream.close();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
